package miblab.school.background;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.lang.Math;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
//import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import miblab.school.SystemFunctions;
import miblab.school.SystemParameters;

public class  GPSCollector extends Service {

	private static  final String TAG = GPSCollector.class.getSimpleName();
	public Location location;
	private double lat;
	private double lon;
	private double time;
	private String place;
	public LocationManager lm;
	public LocationListener ll;
	private String FN;
	boolean status;
	private int interval=15;
	private BroadcastReceiver myBatteryReceiver;	
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i(TAG, "Service creating"); 
	
		//*************************Alarm************************************
		PendingIntent pendingIntent;
		Intent myIntent = new Intent(GPSCollector.this, MyAlarmService.class);
		pendingIntent = PendingIntent.getService(GPSCollector.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

		Calendar calendar = Calendar.getInstance();
		// 11 PM 
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 55);
		calendar.set(Calendar.SECOND, 0);
		
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

		//***************Battery Levels***************************

        /**This registers the receiver for a broadcast message 
         *to be sent when the battery level is changed*/
       
        this.registerReceiver(this.myBatteryReceiver,new IntentFilter(Intent.ACTION_BATTERY_LOW));
         myBatteryReceiver = new BroadcastReceiver()
        {

        	 @Override
        	 public void onReceive(Context arg0, Intent arg1) {
        	  int bLevel = arg1.getIntExtra("level", 0); // gets the battery level
        	  Log.i("Level", ""+bLevel);
        	  // Here you do something useful with the battery level...
        	  if(bLevel>25)
        	  {  
                  interval = 15;
        	  }
        	  else
        		  interval=60;
        	 } 
        };
        
	
		//**********************Initialize Location Variables*******************************	    
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		LocationListener ll = new mylocationlistener();
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,interval*60*1000L,0,ll);

		

	}  

	//**********************Write SD + Append ***************************************************	  
	public boolean SDWrite(String filename, double lt,double ln, double tim, String loc)
	{
		boolean state = false;
		String eol = System.getProperty("line.separator");
		//-------------------------------------------------------------------------------------			
		try
		{
			File root = new File(SystemParameters.path, "School");
			if (!root.exists()) {
				root.mkdirs();
			}

			if(root.canWrite())
			{	 

				File gpxfile = new File(root,filename);
				if(!gpxfile.exists())
				{
					FileWriter writer1 = new FileWriter(gpxfile);
					writer1.write("");
					writer1.close();
				}
				FileInputStream fIn = new FileInputStream(gpxfile);
				BufferedReader myReader = new BufferedReader(
						new InputStreamReader(fIn));
				String aDataRow = "";
				String aBuffer = "";
				while ((aDataRow = myReader.readLine()) != null) { 
					aBuffer += aDataRow + eol;
				}
				myReader.close();
				fIn.close();
				//-------------------------------------------------------------------------------------				
				aBuffer += "Lat:"+lt+":Lon:"+ln+":Tim:"+tim+":Pla:"+loc+eol;
				FileWriter writer = new FileWriter(gpxfile);
				writer.append(aBuffer);
				writer.close();

				state = true;
			}
			else
			{
				//Toast.makeText(this, "SD Card Unreadable", Toast.LENGTH_SHORT).show();
			}
		} 
		//-------------------------------------------------------------------------------------			
		catch(IOException e)
		{
			//Toast.makeText(this, "Insert SD Card", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			state = false;
		}

		return state;
	}

	//**********************Timer intent***************************************************	  
	@Override
	public IBinder onBind(Intent intent) {
			return null;
	}

	//**********************On Destroy***************************************************	 

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "Service destroying");

		lm.removeUpdates(ll); 
		lm = null;

	}


	//**********************Compare Locations***************************************************
	public String Comparelocations(double lt, double ln)
	{
		String loc=null;
		double[] home= new double[2];
		double[] school= new double[2];	 			 
		double[] hospital= new double[2];
		double dhome,dsch,dhosp;
		

		home=SystemFunctions.LatLon("Home.txt");
		school=SystemFunctions.LatLon("School.txt");
		hospital=SystemFunctions.LatLon("Hospital.txt");

		dhome = distFrom(lat,lon,home[0],home[1]);
		dsch = distFrom(lat,lon,school[0],school[1]);	
		dhosp = distFrom(lat,lon,hospital[0],hospital[1]);

		if(dsch<=SystemParameters.threshold)
			loc="School";
		else if(dhome<=SystemParameters.threshold) 
			loc="Home";
		else if(dhosp<=SystemParameters.threshold) 
			loc="Hospital";
		else
			loc="Others";
		return loc;
	}

	//**********************************Distance from Latitudes & Longitudes***************************************
	public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
		double earthRadius = 6371*1000;
		double dLat = Math.toRadians(lat2-lat1);
		double dLng = Math.toRadians(lng2-lng1);
		double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
				Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
				Math.sin(dLng/2) * Math.sin(dLng/2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		double dist = earthRadius * c;

		return dist;
	}



	//**********************location listener***************************************************	  
	class mylocationlistener implements LocationListener {
		@Override
		public void onLocationChanged(Location location) 
		{
			if (location != null) {

				Log.d("LOCATION CHANGED", location.getLatitude() + "");
				Log.d("LOCATION CHANGED", location.getLongitude() + "");
				Log.d("LOCATION CHANGED", location.getTime() + "");
				lat = location.getLatitude();
				lon = location.getLongitude();
				time = location.getTime()/1000;
				place=Comparelocations(lat,lon);
				FN=SystemFunctions.Getfilename();
				status = SDWrite(FN,lat,lon,time,place);
				if(status)
				{
					Log.i(TAG,"Saved");
					
				}
			}

		}
		@Override
		public void onProviderDisabled(String provider) {
		}
		@Override
		public void onProviderEnabled(String provider) {
		}
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};
}